<template>
  <div class="system-menu-container">
<!-- https://miyuesc.github.io/process-designer/ -->
		<div class="system-user-search mb15">
			<el-form :model="param" :inline="true" ref="queryFormRef" @keyup.enter.native="loadList">
				<el-row>
					<el-col :span="8">
							<el-form-item label="模型名称" prop="searchName">
								<el-input  v-model="param.searchName" clearable/>
							</el-form-item>
					</el-col>
					<el-col :span="8">
					</el-col>
					<el-col :span="8">
						<el-button type="primary" class="ml7" @click="loadList">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<div class="home_common background_bg6">
			<div class="btnStyle">
				<el-button  type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
				<el-button type="success"  icon="ele-Upload"  @click="()=>{ this.dialogVisible=true }">导入</el-button>
			</div>
		</div>
		<el-table :data="dataList" border v-loading="listLoading" @selection-change="selectionChangeHandle" style="width: 100%;">
			<el-table-column prop="id" type="selection" width="50"> </el-table-column>
			<el-table-column prop="key" label="流程编码" width="100px"> </el-table-column>
			<el-table-column prop="name" width="200px" label="模型名称"></el-table-column>
			<el-table-column prop="metaInfo" label="描述" :formatter="discription"></el-table-column>
			<el-table-column prop="createTime" width="150" label="创建时间" :formatter="formatDateTime" ></el-table-column>
			<el-table-column prop="lastUpdateTime" width="150" label="最后更新日期" :formatter="formatDateTime" ></el-table-column>
			<el-table-column header-align="center" align="center" width="300" label="操作">
				<template  #default="scope">
					<el-button type="primary" link @click="updateHandle(scope.row.id)" >设计</el-button>
					<el-button type="primary" link @click="deleteHandle(scope.row.id)" >删除</el-button>
					<el-button type="primary" link @click="deployHandle(scope.row)" >发布</el-button>
					<el-button type="primary" link @click="exportXml(scope.row)">导出</el-button>
					<el-button type="primary" link @click="viewHisVersion(scope.row)">历史</el-button>
					<el-button type="primary" link @click="startProcess(scope.row)">发起流程</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			@size-change="onHandleSizeChange"
			@current-change="onHandleCurrentChange"
			:pager-count="5"
			:page-sizes="[10, 50, 200]"
			v-model:current-page="param.page"
			background
			v-model:page-size="param.limit"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total" small>
		</el-pagination>
		<el-dialog title="流程文件导入" v-model="dialogVisible" width="40%" class="customDialog" :close-on-click-modal="false">
			<el-upload class="upload-demo" ref="uploadRef1" :file-list="fileList" :limit="10"
				multiple
				action="#"
				:before-upload="beforeupload"
				:on-exceed="handleExceed"
				:on-success="handleSuccess"
				:on-error="handleError"
				:http-request="uploadFile"
				:with-credentials='true'>
				<template #trigger>
					<el-button type="primary">选取文件</el-button>
				</template>
				<template #tip>
					<div class="el-upload__tip">
						只能上传.xml文件
					</div>
				</template>
			</el-upload>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleClose">取消</el-button>
					<el-button type="primary" @click="submitUpload">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<AddOrUpdate ref="addOrUpdateRef" @refreshDataList="loadList"></AddOrUpdate>
		<DeployVerHis  ref="deployVerHisRef" @refreshDataList="loadList"></DeployVerHis>
		<StartProcess ref="startProcessRef" @refreshDataList="loadList"></StartProcess>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, defineComponent, nextTick } from 'vue'
import type { FormInstance, UploadInstance  } from 'element-plus'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import {workflowApi} from '/@/api/workflowapi'
import StartProcess from './startProcessCommon.vue'
import AddOrUpdate from './AddOrUpdateModel.vue'
import DeployVerHis from './DeployVerHis.vue'
export default defineComponent({
	components: { AddOrUpdate, DeployVerHis, StartProcess },
	setup () {
		const addOrUpdateRef = ref()
		const deployVerHisRef = ref()
		const startProcessRef = ref()
		const uploadRef1 = ref<UploadInstance>()
		const state = reactive({
			listLoading: false,
			dataList: [],
			total: 0,
			totalSelect: 0,
			param: {
				page: 1,
				limit: 10,
				searchName: ''
			},
			dataListSelections: [],
			dialogVisible: false,
			fileList: [],
		})

		// 页面加载时
		onMounted(() => {
			// 列表查询
			loadList()
		})

		//查询
		const loadList = () => {
			state.listLoading = true
			workflowApi().queryModelList(state.param).then(data => {
				if (data && data.code === 0) {
					state.dataList = data.page.list
					state.total = data.page.totalCount
				} else {
					state.dataList = []
					state.total = 0
				}
			}).catch(() => {
			}).finally(() => {
				state.listLoading = false
			})
		}
		//重置
		const reSetForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.resetFields()
			state.param.page = 1
			loadList()
		}

		// 分页改变
		const onHandleSizeChange = (val: number) => {
			state.param.limit = val;
			loadList()
		}
		// 分页改变
		const onHandleCurrentChange = (val: number) => {
			state.param.page = val;
			loadList()
		}

		const discription = (row: any, column: any, cellValue: any) => {
			let metaInfo = JSON.parse(cellValue)
			return metaInfo.description
		}

		//新增
		const addOrUpdateHandle = () => {
			workflowApi().modelAdd().then(data => {
				addOrUpdateRef.value.openDialog(data.id, true)
			}).catch(err => {
				// console.log(err)
			})
		}

		// 设计
		const updateHandle = (id: string) => {
			addOrUpdateRef.value.openDialog(id, false)
		}

		// 删除
		const deleteHandle = (id: string) => {
			ElMessageBox.confirm('是否确定删除', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				var ids = id ? [id] : state.dataListSelections.map(item => {
					return item.id
				})
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				workflowApi().modelDeleteById(id).then((data) => {
					if (data && data.code === 0) {
						ElMessage.success('删除成功！')
						loadList()
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error('删除失败！')
				}).finally(() => {
					loading.close()
				})
			})
		}

		//上传文件
		const submitUpload = () => {
			let formData = new FormData()
			nextTick(() => {
				state.fileList.forEach((val, index) => {
					formData.append('file', val.raw)
				})
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				workflowApi().uploadModelFile(formData).then(data => {
					if (data && data.code === 0) {
						ElMessage.success('上传成功！')
						handleClose()
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error('上传失败！')
				}).finally(() => {
					loading.close()
				})
			})
			
		}

		//取消上传
		const handleClose = () => {
			state.dialogVisible = false
			uploadRef1.value!.clearFiles()
			state.fileList = []
			loadList()
		}
		
		const beforeupload = (file: any) => {
			var filename = file.name != null ? file.name : ''
			if (filename.indexOf('.xml') < 0) {
				ElMessage.error('只能导入xml文件')
				return false
			}
			return true
		}
		const handleExceed =  (files: any, fileList: any) => {
			ElMessage.error('一次只能导入10个文件！')
		}
		const handleSuccess = (response: any, file: any, fileList: any) => {
			// console.log(response.code)
			if (response.code === 0) {
				ElMessage.success('上传成功！')
			} else {
				ElMessage.error('上传失败！')
			}
		}
		const handleError = (err: any, file: any, fileList: any) => {
			ElMessage.error('上传失败！')
		}
		const uploadFile = (file: any) => {
		// console.log(file.name)
		}

		//导出
		const exportXml = (row: any) => {
			workflowApi().exportXml(row.deploymentId)
		}
		// 发布流程
		const deployHandle = (row: any) => {
			const loading = ElLoading.service({
				lock: true,
				text: '处理中',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			workflowApi().modelDeploy(row.id).then(data => {
				if (data.code === 0) {
					ElMessage.success('流程发布成功')
					loadList()
				} else {
					ElMessage.error('流程发布失败')
				}
			})
			.catch(() => {
				ElMessage.error('流程发布失败')
			}).finally(() => {
				loading.close()
			})
		}
		const viewHisVersion = (row: any) => {
			workflowApi().getProcessDefinition(row.deploymentId).then((data) => {
				if (data && data.code === 0) {
					deployVerHisRef.value.openDialog(data.def.id, row.key, row.deploymentId)
				} else {
					ElMessage.error('获取流程历史版本失败')
				}
			}).catch(() => {
				ElMessage.error('获取流程历史版本失败')
			})
		}
		// 发起流程
		const startProcess = (row: any) => {
			startProcessRef.value.openDialog(row.name, row.key)
		}
		return {
			loadList,
			reSetForm,
			onHandleSizeChange,
			onHandleCurrentChange,
			addOrUpdateHandle,
			updateHandle,
			addOrUpdateRef,
			uploadRef1,
			deleteHandle,
			submitUpload,
			handleClose,
			beforeupload,
			handleExceed,
			handleSuccess,
			handleError,
			uploadFile,
			exportXml,
			deployHandle,
			deployVerHisRef,
			startProcessRef,
			viewHisVersion,
			startProcess,
			...toRefs(state),
		}
	}
})
</script>

<style>

</style>